//
//  ComPoseViewController.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/17.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import SVProgressHUD

//文字限制长度
let numberLine = 140

class ComPoseViewController: UIViewController,UITextViewDelegate {

    
    //键盘输入的视图
    private lazy var emotionVC:EmotionViewController  = EmotionViewController {[weak self] (emotion) -> () in
        
        self?.textView.insertEmoticon(emotion)
        
    }
    //照片选择控制器
    private lazy var photoSelecttroVC:PhotoSelectorViewController = PhotoSelectorViewController()

    //关闭微博
    func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发送微博
    func sendStatus() {
//         判断文字发布微博长短
            let text = self.textView.emoticonText
        
            if text.characters.count > numberLine {
                SVProgressHUD.showInfoWithStatus("文本太长", maskType: SVProgressHUDMaskType.Gradient)
                return
            }
            
            //发布图片微博
            let image = photoSelecttroVC.photos.last
        
            NetWorkingTools.sharedTools.sendStatus(text,image:image, finished: { (result, error) -> () in
                
                if error != nil {
                SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Gradient)
                    
                    return
                }
             self.close()
        })
    }
    
    func inputEmoticon() {
        
        //注销键盘
        textView.resignFirstResponder()
        //设置输入键盘
        textView.inputView = (textView.inputView == nil) ? emotionVC.view :nil

        //激活键盘
        textView.becomeFirstResponder()
        
    }
    
    //UITextViewDelegate代理方法
    func textViewDidChange(textView: UITextView) {
       //设置占位标签和按钮
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        //设置长度文字的颜色和数值
        let text = textView.emoticonText
        let len = numberLine - text.characters.count
        
        lenghtLabel.text = "\(len)"
        lenghtLabel.textColor = len < 0 ?UIColor.redColor() : UIColor.lightGrayColor()
        
    }
    
    //搭建界面
    override func loadView() {
        view = UIView()
        //凡是视图控制器，都要有背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        //1视图层次
        view.addSubview(textView)
        view.addSubview(photoSelecttroVC.view)
        view.addSubview(toobar)
        
        //2添加子控制器。
        addChildViewController(photoSelecttroVC)
        
        //3准备界面
        prepareNav()
        preparToolbar()
        preparTextView()
        preparPhotoView()
        
    }
    //准备诈骗片选择视图
    private func preparPhotoView() {

        //自动布局
        var s = UIScreen.mainScreen().bounds.size
        //swift允许直接修改结构体的属性
        s.height = 0.6 * s.height
     
        photoSelecttroVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
    }
    
    //不要再此使用view做参照,键盘监听方法
    override func viewDidLoad() {
        super.viewDidLoad()
        addKeyboardObserssver()
    }
    deinit{
      removeKeyboardobserssver()
    }
    
    //注册通知
    private func addKeyboardObserssver() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    //移除通知
    private func removeKeyboardobserssver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //键盘变化监听方法
    func keyboardChanged(n:NSNotification) {
        
        //动画时间选项
        let cruve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        // 获取目标 frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        // 设置约束
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        // 动画
        UIView.animateWithDuration(duration) {
            
            //设置动画时间选项
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: cruve)!)
            
            self.view.layoutIfNeeded()
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 激活键盘
        textView.becomeFirstResponder()
    }
    
    //底部约束
    private var toolbarBottomCons: NSLayoutConstraint?
    
    //准备textView文本框
    private func preparTextView() {
        
        textView.backgroundColor = UIColor.whiteColor()
        //自动布局
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toobar, size: nil)
        //添加占位标签
        placeholderLabel.text = "分享趣闻喽......."
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
        //将限制文字添加到view
        view.addSubview(lenghtLabel)
        lenghtLabel.sizeToFit()
        lenghtLabel.text = String(numberLine)
        
        lenghtLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
        
    }
    
    //准备toolbar
    private func preparToolbar() {
        
        toobar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        //布局
       let cons = toobar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
//        //记录底部约束
            toolbarBottomCons = toobar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        //准备一个数组
        let itemSetting = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSetting {
            
           items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            
            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //删除最后一个item
        items.removeLast()
        
        //设置toorbar的itemes
        toobar.items = items
    }
    //准备导航栏
    private func prepareNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
         navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        //先设置发送微博为不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        //设置标题栏
        let textView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
        
        let titleLabel = UILabel(Color: UIColor.blackColor(), fontSize: 15)
        titleLabel.text = "发布微博"
        titleLabel.sizeToFit()
        textView.addSubview(titleLabel)
        //文字居中
        titleLabel.ff_AlignVertical(type: ff_AlignType.CenterCenter, referView: textView, size: nil)
        
        let namelabel = UILabel(Color: UIColor.darkGrayColor(), fontSize: 11)
        namelabel.text = UserAccount.shareAccount?.name ?? ""
        namelabel.sizeToFit()
        titleLabel.addSubview(namelabel)
        //自动布局
         namelabel.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: titleLabel, size: nil)
        
        navigationItem.titleView = textView
      
    }

    //懒加载控件
    private lazy var textView:UITextView = {
        let text = UITextView()
        text.delegate = self
        text.font = UIFont.systemFontOfSize(18)
        //允许垂直拖拽
        text.alwaysBounceVertical = true
        //拖拽关闭键盘
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return text
    }()
    //数字标签，限制长度
    private lazy var lenghtLabel = UILabel(Color: UIColor.lightGrayColor(), fontSize: 14)
    
    //占位标签
    private lazy var placeholderLabel = UILabel(Color: UIColor.darkGrayColor(), fontSize: 18)
    //文本视图
    private lazy var toobar = UIToolbar()
}
